<template>
  <div class="role-add-container">
    <div class="page-header">
      <div class="header-title">
        <h2>{{ isEdit ? '编辑角色' : '添加角色' }}</h2>
        <span class="subtitle">{{ isEdit ? '修改角色信息' : '创建新的系统角色' }}</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <el-card class="form-container" shadow="hover">
      <el-form
        :model="roleForm"
        :rules="roleRules"
        ref="roleFormRef"
        label-width="120px"
        :disabled="loading"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" :disabled="isEdit" placeholder="请输入角色编码，格式如ROLE_XXX" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        
        <el-divider>权限设置</el-divider>
        
        <el-form-item label="权限配置" prop="permissions">
          <div class="permission-tree-container">
            <el-tree
              ref="permissionTree"
              :data="permissionTree"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkedPermissions"
              :props="{
                label: 'name',
                children: 'children'
              }"
            />
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const roleFormRef = ref(null);
const permissionTree$ = ref(null);

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.query.id !== undefined;
});

// 角色表单数据
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: ''
});

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    name: '小区管理',
    children: [
      { id: 101, name: '查看小区列表' },
      { id: 102, name: '添加小区' },
      { id: 103, name: '编辑小区' },
      { id: 104, name: '删除小区' }
    ]
  },
  {
    id: 2,
    name: '房产管理',
    children: [
      { id: 201, name: '查看栋数列表' },
      { id: 202, name: '添加栋数' },
      { id: 203, name: '编辑栋数' },
      { id: 204, name: '删除栋数' },
      { id: 205, name: '查看房产列表' },
      { id: 206, name: '添加房产' },
      { id: 207, name: '编辑房产' },
      { id: 208, name: '删除房产' }
    ]
  },
  {
    id: 3,
    name: '人员管理',
    children: [
      { id: 301, name: '查看业主列表' },
      { id: 302, name: '添加业主' },
      { id: 303, name: '编辑业主' },
      { id: 304, name: '删除业主' },
      { id: 305, name: '查看车辆列表' },
      { id: 306, name: '添加车辆' },
      { id: 307, name: '编辑车辆' },
      { id: 308, name: '删除车辆' }
    ]
  },
  {
    id: 4,
    name: '车位管理',
    children: [
      { id: 401, name: '查看车位列表' },
      { id: 402, name: '添加车位' },
      { id: 403, name: '编辑车位' },
      { id: 404, name: '删除车位' },
      { id: 405, name: '查看使用记录' },
      { id: 406, name: '添加使用记录' },
      { id: 407, name: '编辑使用记录' },
      { id: 408, name: '删除使用记录' }
    ]
  },
  {
    id: 5,
    name: '服务管理',
    children: [
      { id: 501, name: '查看活动列表' },
      { id: 502, name: '添加活动' },
      { id: 503, name: '编辑活动' },
      { id: 504, name: '删除活动' },
      { id: 505, name: '查看报修列表' },
      { id: 506, name: '处理报修' },
      { id: 507, name: '查看投诉列表' },
      { id: 508, name: '处理投诉' },
      { id: 509, name: '查看信箱列表' },
      { id: 510, name: '回复信箱' }
    ]
  },
  {
    id: 6,
    name: '系统管理',
    children: [
      { id: 601, name: '查看用户列表' },
      { id: 602, name: '添加用户' },
      { id: 603, name: '编辑用户' },
      { id: 604, name: '删除用户' },
      { id: 605, name: '查看角色列表' },
      { id: 606, name: '添加角色' },
      { id: 607, name: '编辑角色' },
      { id: 608, name: '删除角色' },
      { id: 609, name: '查看权限列表' },
      { id: 610, name: '权限配置' }
    ]
  }
]);

// 选中的权限ID
const checkedPermissions = ref([]);

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^ROLE_[A-Z_]+$/, message: '角色编码格式应为ROLE_XXX', trigger: 'blur' }
  ]
};

// 初始化
onMounted(async () => {
  if (isEdit.value) {
    await fetchRoleData();
  }
});

// 获取角色数据
const fetchRoleData = async () => {
  const roleId = route.query.id;
  if (!roleId) return;
  
  loading.value = true;
  try {
    // 模拟API调用
    // const token = localStorage.getItem('token');
    // const response = await axios.get(`/api/roles/${roleId}`, {
    //   headers: { Authorization: `Bearer ${token}` }
    // });
    
    // 填充表单
    // const roleData = response.data;
    // roleForm.id = roleData.id;
    // roleForm.name = roleData.name;
    // roleForm.code = roleData.code;
    // roleForm.description = roleData.description || '';
    
    // 模拟数据
    if (roleId == 1) {
      roleForm.id = 1;
      roleForm.name = '超级管理员';
      roleForm.code = 'ROLE_ADMIN';
      roleForm.description = '系统超级管理员，拥有所有权限';
      checkedPermissions.value = getAllPermissionIds();
    } else if (roleId == 2) {
      roleForm.id = 2;
      roleForm.name = '小区管理员';
      roleForm.code = 'ROLE_MANAGER';
      roleForm.description = '小区管理员，负责管理指定小区';
      checkedPermissions.value = [
        101, 102, 103, 104, 
        201, 202, 203, 204, 205, 206, 207, 208,
        301, 302, 303, 304, 305, 306, 307, 308,
        401, 402, 403, 404, 405, 406, 407, 408,
        501, 502, 503, 504, 505, 506, 507, 508, 509, 510
      ];
    } else if (roleId == 3) {
      roleForm.id = 3;
      roleForm.name = '业主';
      roleForm.code = 'ROLE_OWNER';
      roleForm.description = '业主用户，可以查看自己的房产和提交服务请求';
      checkedPermissions.value = [505, 506, 507, 508, 509];
    } else if (roleId == 4) {
      roleForm.id = 4;
      roleForm.name = '普通员工';
      roleForm.code = 'ROLE_STAFF';
      roleForm.description = '物业普通员工，处理日常事务';
      checkedPermissions.value = [
        101, 201, 205, 301, 305, 401, 405, 
        501, 505, 506, 507, 508, 509, 510
      ];
    }
  } catch (error) {
    console.error('获取角色数据失败:', error);
    ElMessage.error('获取角色数据失败');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return;
  
  await roleFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    try {
      // 获取选中的权限ID
      const permissionTree = permissionTree$.value;
      const checkedKeys = permissionTree ? permissionTree.getCheckedKeys() : [];
      const halfCheckedKeys = permissionTree ? permissionTree.getHalfCheckedKeys() : [];
      const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
      
      // 准备提交的数据
      const submitData = { 
        ...roleForm,
        permissions: allCheckedKeys
      };
      
      // 模拟API调用
      // const token = localStorage.getItem('token');
      // const headers = { Authorization: `Bearer ${token}` };
      
      if (isEdit.value) {
        // 更新角色
        // await axios.put(`/api/roles/${roleForm.id}`, submitData, { headers });
        ElMessage.success('角色更新成功');
      } else {
        // 创建角色
        // await axios.post('/api/roles', submitData, { headers });
        ElMessage.success('角色创建成功');
      }
      
      // 返回列表页
      goBack();
    } catch (error) {
      console.error('保存角色失败:', error);
      ElMessage.error('保存角色失败: ' + (error.response?.data?.message || error.message));
    } finally {
      loading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  roleFormRef.value?.resetFields();
  if (!isEdit.value) {
    checkedPermissions.value = [];
  }
};

// 返回列表页
const goBack = () => {
  router.push('/system/role');
};

// 获取所有权限ID
const getAllPermissionIds = () => {
  const ids = [];
  
  const extractIds = (nodes) => {
    if (!nodes) return;
    
    nodes.forEach(node => {
      ids.push(node.id);
      if (node.children) {
        extractIds(node.children);
      }
    });
  };
  
  extractIds(permissionTree.value);
  return ids;
};
</script>

<style scoped>
.role-add-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-container .el-form {
  padding: 20px 0;
}

.permission-tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 10px;
}
</style> 